//购物车
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { insertCartAPI, getCartListAPI,delCartAPI } from '@/apis/cart'
export const useCartStore = defineStore('cart', () => {
   //用户实例对象
   const userStore = useUserStore()
   // 判断是否是登录状态
   const isLogin = computed(() => userStore.userInfo.token)
   //1.定义cartList数据，存储购物车商品列表
   const cartList = ref([])
   //2.定义addToCart方法，添加商品到购物车
   const addToCart = async (goods) => {
      //从goods中获取skuId和count
      const { skuId, count } = goods
      //判断是否登录
      if (isLogin.value) {
         // 登录之后的加入购车逻辑
         await insertCartAPI({ skuId, count })
         //获取最新购物车列表
         getCartList()
      } else {
         // 未登录的加入购物车逻辑
         const item = cartList.value.find(item => item.skuId === goods.skuId)
         if (item) {
            item.count += 1
         } else {
            cartList.value.push(goods)
         }
      }
   }
   //获取最新购物车列表
   const getCartList = async () => {
      const res = await getCartListAPI()
      cartList.value = res.data.result
   }
   //清除购物车
   const clearCart = () => {
      cartList.value = []
   }
   //删除购物车
   const removeFromCart = async (skuId) => {
      //判断是否登录
      if (isLogin.value) {
         // 登录之后的删除购物车逻辑
         await delCartAPI([skuId])
         //获取最新购物车列表
         getCartList()
      } else {
         const index = cartList.value.findIndex(item => item.skuId === skuId)
         cartList.value.splice(index, 1)
      }
   }
   // 单选功能
   const singleCheck = (skuId, selected) => {
      // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
   }
   //是否全选
   const isAll = computed(() => {
      return cartList.value.every(item => item.selected)
   })
   // 全选功能
   const allCheck = (selected) => {
      cartList.value.forEach(item => {
         item.selected = selected
      })
   }
   //已经选择数量
   const selectedCount = computed(() => {
      return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
   })
   //已经选择商品合计
   const selectedPrice = computed(() => {
      return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
   })
   // 计算属性
   // 1. 总的数量 所有项的count之和
   const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
   // 2. 总价 所有项的count*price之和
   const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
   return {
      cartList,
      addToCart,
      allCount,
      allPrice,
      removeFromCart,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      clearCart,
      getCartList
   }
}, {
   persist: true,
})